﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Reviewer.Entities;
using System.Data;
using System.Collections.ObjectModel;
using System.Globalization;
using Reviewer.Utilities.Data;
using MySql.Data.MySqlClient;
using Reviewer.Data.Bases;
using System.Data.SqlClient;

namespace Reviewer.Data
{
    /// <summary>
    /// News Repository
    /// </summary>
    [CLSCompliant(false)]
    public class FrontPagePostRepository : RepositoryCrudBase<FrontPagePost, Int32>
    {
        #region fields (private)
        private const string TABLE_NAME = "V2_ForsidePost";
        private static readonly CrudColumnInfo columnId = new CrudColumnInfo(0, "Id", MySqlDbType.Int32, true, false, false, true);
        private static readonly CrudColumnInfo columnTitle = new CrudColumnInfo(1, "Titel", MySqlDbType.VarChar, 255, false, false, true);
        private static readonly CrudColumnInfo columnPostType = new CrudColumnInfo(1, "ForsideType", MySqlDbType.VarChar, 255, false, false, true);
        private static readonly CrudColumnInfo columnText = new CrudColumnInfo(2, "Tekst", MySqlDbType.VarChar, 255, false, false, true);
        private static readonly CrudColumnInfo columnLink = new CrudColumnInfo(3, "Link", MySqlDbType.VarChar, 255, false, false, true);
        private static readonly CrudColumnInfo columnImageId = new CrudColumnInfo(4, "BilledID", MySqlDbType.VarChar, 255, false, false, true);
        private static readonly CrudColumnInfo columnDate = new CrudColumnInfo(5, "Dato", MySqlDbType.Date, false, false, true);
        private static readonly CrudColumnInfo columnActive = new CrudColumnInfo(5, "Aktiv", MySqlDbType.VarChar, 255, false, false, true);
        #endregion

        #region methods (public)
        public Collection<FrontPagePost> Select(bool isActive, int maxResults)
        {
            using (MySqlCommand command = new MySqlCommand())
            {
                command.CommandText = String.Format(CultureInfo.InvariantCulture
                    , "{0} WHERE {1} = @{1} ORDER BY {2} DESC"
                    , this.SelectAllQuery()
                    , FrontPagePostRepository.columnActive.Name
                    , FrontPagePostRepository.columnId.Name);
                
                if (maxResults > 0)
                {
                    command.CommandText += " LIMIT " + maxResults.ToString(CultureInfo.InvariantCulture);
                }

                FrontPagePostRepository.columnActive.AddParameter(command, isActive);

                return base.ExecuteReaderAndBuildList(command);
            }
        }

        public ICollection<FrontPagePost> SelectAll(int topCount)
        {
            return base.SelectAll(topCount, FrontPagePostRepository.columnId, SortOrder.Descending);
        }
        #endregion

        #region methods (protected)
        internal override CrudColumnInfo[] Columns
        {
            get
            {
                return new CrudColumnInfo[]{
                    FrontPagePostRepository.columnId
                    , FrontPagePostRepository.columnTitle
                    , FrontPagePostRepository.columnPostType
                    , FrontPagePostRepository.columnText
                    , FrontPagePostRepository.columnLink
                    , FrontPagePostRepository.columnImageId
                    , FrontPagePostRepository.columnDate
                    , FrontPagePostRepository.columnActive};
            }
        }

        protected override string TableName
        {
            get { return FrontPagePostRepository.TABLE_NAME; }
        }

        internal override object ColumnToValue(CrudColumnInfo info, FrontPagePost item)
        {
            if (info.Equals(FrontPagePostRepository.columnId)) return item.Id;
            else if (info.Equals(FrontPagePostRepository.columnTitle)) return item.Title;
            else if (info.Equals(FrontPagePostRepository.columnPostType)) return item.PostType;
            else if (info.Equals(FrontPagePostRepository.columnText)) return item.Text;
            else if (info.Equals(FrontPagePostRepository.columnLink)) return item.Link;
            else if (info.Equals(FrontPagePostRepository.columnImageId)) return item.ImageId;
            else if (info.Equals(FrontPagePostRepository.columnDate)) return item.Date.Date.ToString("dd-MM-yyyy", CultureInfo.InvariantCulture);
            else if (info.Equals(FrontPagePostRepository.columnActive)) return item.IsActive;
            return null;
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        protected override FrontPagePost BuildItemFromReader(IDataReader reader)
        {
            FrontPagePost item = new FrontPagePost();
            if (reader != null)
            {
                item.Id = DataReaderUtility.GetValue(reader, reader.GetOrdinal(FrontPagePostRepository.columnId.Name), 0);
                item.Title = DataReaderUtility.GetValue(reader, reader.GetOrdinal(FrontPagePostRepository.columnTitle.Name), String.Empty);
                item.PostType = DataReaderUtility.GetValue(reader, reader.GetOrdinal(FrontPagePostRepository.columnPostType.Name), String.Empty);
                item.Text = DataReaderUtility.GetValue(reader, reader.GetOrdinal(FrontPagePostRepository.columnText.Name), String.Empty);
                item.Link = DataReaderUtility.GetValue(reader, reader.GetOrdinal(FrontPagePostRepository.columnLink.Name), String.Empty);
                item.ImageId = DataReaderUtility.GetValue(reader, reader.GetOrdinal(FrontPagePostRepository.columnImageId.Name), 0);
                item.IsActive = DataReaderUtility.GetValue(reader, reader.GetOrdinal(FrontPagePostRepository.columnActive.Name), false);

                try
                {
                    item.Date = DataReaderUtility.GetValue(reader, reader.GetOrdinal(FrontPagePostRepository.columnDate.Name), DateTime.MinValue);
                }
                catch
                {
                    item.Date = DateTime.MinValue;
                }

                if (item.Date.Equals(DateTime.MinValue))
                {
                    string dateString = DataReaderUtility.GetValue(reader, reader.GetOrdinal(FrontPagePostRepository.columnDate.Name), String.Empty);
                    if (dateString != DateTime.MinValue.Date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))
                    {
                        string[] dateValueParts = new string[0];
                        if (dateString.IndexOf("-", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            dateValueParts = dateString.Split('-');
                            if (dateValueParts.Length == 3)
                            {
                                if (dateValueParts[2].Length == 4)
                                {
                                    Array.Reverse(dateValueParts);
                                }

                                if (dateValueParts[0].Length == 4)
                                {
                                    dateString = String.Join(CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator, dateValueParts);
                                    item.Date = DateTime.ParseExact(dateString, "yyyy-MM-dd", CultureInfo.CurrentCulture);
                                }
                            }
                        }
                        else if (dateString.IndexOf("/", StringComparison.OrdinalIgnoreCase) > -1)
                        {
                            dateValueParts = dateString.Split('/');
                            dateString = String.Join(CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator, dateValueParts);
                            item.Date = DateTime.ParseExact(dateString, "M" + (dateValueParts[0].Length > 1 ? "M" : "") + "-d" + (dateValueParts[1].Length > 1 ? "d" : "") + "-yyyy", CultureInfo.CurrentCulture);
                        }
                    }
                }
            }
            return item;
        }
        #endregion
    }
}
